var express = require('express');
var router = express.Router();
var mongoose=require("../db/db")
let { cooperativeModel,areaModel ,pointModel} = require('../db/tian')
/* GET home page. */
function setRouter (url, model) {
  router.get(`/${url}`, async (req, res, next) => {
    let name = RegExp(req.query.name)
    let page = req.query.page
    let size = req.query.pagesize
    let data = await model.find({ name: name }).skip((page - 1) * size).limit(size)
    let count = await model.count()
    res.send({
      code: 200,
      data,
      count
    })
  });
  router.get(`/${url}/:_id`, async (req, res, next) => {
    try {
      await model.deleteOne({ _id: req.params._id })
      res.send({
        code: 200
      })
    } catch (error) {
      res.send({
        code: 500
      })
    }
  });
  router.post(`/${url}`, async (req, res, next) => {
    try {
      await model.create(req.body)
      res.send({
        code: 200
      })
    } catch (error) {
      res.send({
        code: 500
      })
    }
  });
  router.put(`/${url}/:_id`, async (req, res, next) => {
    try {
      await model.updateOne({ _id: req.params._id }, req.body)
      res.send({
        code: 200
      })
    } catch (error) {
      res.send({
        code: 500
      })
    }
  });
  router.delete(`/${url}/:_id`, async (req, res, next) => {
    try {
      await model.deleteOne({ _id: req.params._id })
      res.send({
        code: 200
      })
    } catch (error) {
      res.send({
        code: 500
      })
    }
  });
}
router.get('/pointss',async(req,res)=>{
  let data = await pointModel.find()
  res.send({
    code:200,
    data
  })
})
router.get(`/points`, async (req, res, next) => {
  let name = RegExp(req.query.name)
  let page = req.query.page
  let size = req.query.pagesize
  let data = await pointModel.find({ name: name }).populate("area").populate("cooperative").skip((page - 1) * size).limit(size)
  data=data.map((i)=>{
    return {
      _id:i._id,
      name:i.name,
      area:i.area._id,
      areaname:i.area.name,
      lei:i.lei,
      cooperative:i.cooperative._id,
      cooperativename:i.cooperative.name,
      di:i.di,
      xidi:i.xidi,
    }
  })
  if(req.query.area!==""){
    data=data.filter((i)=>{
      return i.area==req.query.area
    })
  }
  let count = await pointModel.count()
  res.send({
    code: 200,
    data,
    count
  })
});
router.get(`/cooperative/:id`, async (req, res, next) => {
    let data=await areaModel.aggregate([{ 
      $lookup: {
        from: "point", // 数据库中关联的集合名
        localField: "_id", // area文档中关联的字段
        foreignField: "area", // book文档中关联的字段
        as: "point" // 返回数据的字段名
      }
    }]);
    
  data=data.filter(i=>i._id==req.params.id)
  res.send({
    code: 200,
    data
  })
});
setRouter("cooperative", cooperativeModel)
setRouter("area",areaModel)
setRouter("point",pointModel)

module.exports = router;
